from enum import Enum

from django.db import models
from datetime import datetime, timedelta
# Create your models here.

from django.db.models import IntegerField


# class DateTimeFieldFormat(models.DateTimeField):
#     """
#     数据库datetime类型字段格式化(%Y-%m-%d %H:%M:%S)
#     precision:需要保留的小数位数
#     """
#     def __init__(self, verbose_name=None, name=None, precision=0, **kwargs):
#         self.precision = precision
#         super().__init__(verbose_name, name, **kwargs)
#
#     def db_type(self, connection):
#         return 'datetime(%d)' % self.precision


class PublicModel(models.Model):
    CreatedTime = models.DateTimeField(verbose_name='注册时间', auto_now_add=True)
    UpdatedTime = models.DateTimeField(verbose_name='最近修改时间', auto_now=True)

    class Meta:
        abstract = True
        ordering = ['id']


#用户角色
class Roleinfo(models.IntegerChoices):
    superuserman = 0, "超级管理员"
    userman = 1, "普通用户"
    guestuserman = 2, "录单员"


class Role(models.IntegerField):
    rolename = models.CharField(choices=Roleinfo.choices, default=Roleinfo.userman, help_text="用户信息")


#用户信息表
class UserInfo(PublicModel, models.Model):
    '''用户信息表'''
    username = models.CharField(verbose_name='账号', unique=True, max_length=32)
    password = models.CharField(verbose_name='密码', max_length=255)
    name = models.CharField(verbose_name='姓名', max_length=32)
    phone = models.CharField(verbose_name='手机号', max_length=11)
    level = models.IntegerField(verbose_name='用户等级', default=1)  #1为普通用户   10为管理员


class Ap1Info(PublicModel, models.Model):
    '''项目1表'''
    # CreatedAt=models.DateTimeField(verbose_name='创建时间',auto_now_add=True)
    # UpdatedAt=models.DateTimeField(verbose_name='最近修改时间',auto_now=True)
    #项目
    project = models.CharField(verbose_name='项目', max_length=255)
    #类别
    mode = models.CharField(verbose_name='类别', max_length=64)
    #名称
    name = models.CharField(verbose_name='名称', max_length=255)
    #信息
    msg = models.CharField(verbose_name='信息', max_length=255)
    #数量
    count = models.IntegerField(verbose_name='数量')
    #单价
    price = models.DecimalField(verbose_name='单价', max_digits=10, decimal_places=2)
    #备注
    remark = models.CharField(verbose_name='备注', max_length=255, blank=True)


class CDZName(PublicModel, models.Model):
    '''充电桩管理员'''
    prepaidCard = models.CharField(verbose_name='会员ID', max_length=255, unique=True)
    username = models.CharField(verbose_name='名称', unique=True, max_length=32)


class CDZInfo(PublicModel, models.Model):
    orderNum = models.CharField(verbose_name='订单号', max_length=255, db_column="orderNum", unique=True)
    licensePlate = models.CharField(verbose_name='车牌号', max_length=255, db_column="licensePlate")
    carCode = models.CharField(verbose_name='VIN号', max_length=255, db_column="carCode", null=True, blank=True)
    cardType = models.CharField(verbose_name='充电类型', max_length=255, db_column="cardType")
    chargeAmount = models.DecimalField(verbose_name='充电金额', max_digits=10, decimal_places=2,
                                       db_column="chargeAmount", default=0.0)
    chargeElec = models.DecimalField(verbose_name='充电电量', max_digits=10, decimal_places=2, db_column="chargeElec",
                                     default=0.0)
    chargeStartTime = models.DateTimeField(verbose_name='充电开始时间', null=True, db_column="chargeStartTime")
    chargeEndTime = models.DateTimeField(verbose_name='充电结束时间', null=True, db_column="chargeEndTime")
    deviceId = models.CharField(verbose_name='充电设备ID', max_length=255, db_column="deviceId")
    deviceName = models.CharField(verbose_name='充电设备', max_length=255, db_column="deviceName")
    endType = models.CharField(verbose_name='结束原因', max_length=255, db_column="endType", null=True, blank=True)
    prepaidCard = models.CharField(verbose_name='会员ID', max_length=255, db_column="prepaidCard")
    idCardname = models.CharField(verbose_name='名称', max_length=255, db_column="idCardname", null=True, blank=True)

    class Meta:
        verbose_name = "CDZ订单管理"
        verbose_name_plural = verbose_name
        ordering = ['-chargeStartTime']


#自定义表
class Status(models.TextChoices):
    Completed = '1', "已完成"
    Unfinished = '2', "未完成"


class Address(PublicModel, models.Model):
    name = models.CharField(verbose_name='项目名称', max_length=255, unique=True)
    username = models.CharField(verbose_name='联系人', max_length=255)


class PhonoManageInfo(PublicModel, models.Model):
    status_id = (
        (1, u"已完成"),
        (2, u"未完成")
    )

    project = models.CharField(verbose_name='项目', max_length=255)
    custom_date = models.CharField('单据', max_length=32, editable=False)
    # address=models.ForeignKey(to=Address, to_field='name', on_delete=models.CASCADE, null=True, verbose_name="项目信息")
    phono = models.CharField(verbose_name='手机号', max_length=11)
    claid = models.CharField(verbose_name='组ID', max_length=255)
    username = models.CharField(verbose_name='车牌', max_length=255)
    remark = models.CharField(verbose_name='备注', max_length=255, blank=True)
    statu = models.IntegerField(choices=status_id, default=2, verbose_name="状态")

    # def save(self, *args, **kwargs):
    #     # 在保存之前设置custom_date字段
    #     # 注意：这里我们假设你想要的是"YYYYMMDD+"这样的格式
    #     # 其中YYYYMMDD是当天的日期
    #     today_date_str = datetime.now().strftime("%Y%m%d%H%M%S")
    #     self.custom_date = 'DD' + today_date_str
    #
    #     # 调用父类的save方法来实际保存模型
    #     super().save(*args, **kwargs)


class Iphoneinfo(models.Model):
    phono = models.CharField(verbose_name='手机号', max_length=11, unique=True)


class Ap2Info(PublicModel, models.Model):
    status_choices = (
        (1, 'State 1'),
        (2, 'State 2'),
    )
    project = models.CharField(verbose_name='项目', max_length=255)
    #phono=models.ForeignKey(to=Iphoneinfo, to_field='phono', on_delete=models.CASCADE,  verbose_name="手机号")
    phone = models.CharField(verbose_name='号码', max_length=11, blank=True)
    claid = models.CharField(verbose_name='使用地', max_length=255, blank=True)
    username = models.CharField(verbose_name='时间', max_length=255, blank=True)
    remark = models.CharField(verbose_name='系统显示标识', max_length=255, blank=True)
    statu = models.IntegerField(choices=status_choices)
    account = models.CharField(verbose_name='写入数据的账号', max_length=32)


#入场
class ManageUser(PublicModel, models.Model):
    username = models.CharField(verbose_name='联系人', max_length=255, unique=True)
    phono = models.CharField(verbose_name='手机号', max_length=11, unique=True)


class InPark(PublicModel, models.Model):
    indate = models.CharField(verbose_name='入场时间', max_length=255)
    username = models.CharField(verbose_name='联系人', max_length=255)
    phono = models.CharField(verbose_name='手机号', max_length=11, unique=True)
    ilist = models.CharField(verbose_name='物料表', max_length=255, null=True)
    pic = models.CharField(verbose_name='现场图', max_length=255, null=True)
    username_park = models.ForeignKey(to=ManageUser, to_field='username', on_delete=models.CASCADE,
                                      verbose_name="负责人")
    status = models.CharField(verbose_name="状态", max_length=32)
    remark = models.CharField(verbose_name='备注', max_length=255, blank=True)


#url管理
class SubCategory(models.Model):
    name = models.CharField("分类别名称", max_length=10, null=True, blank=True)

    class Meta:
        verbose_name = "子分类"
        verbose_name_plural = verbose_name
        ordering = ['id']


class Site(PublicModel, models.Model):
    url = models.CharField('网站链接', max_length=256, default='', null=True, blank=True)
    logo_url = models.CharField('logo链接', max_length=256, default='', null=True, blank=True)
    name = models.CharField('网站名称', max_length=20, null=True, blank=True)
    describtion = models.TextField('网站简介', null=True, blank=True)
    is_show = models.BooleanField('是否展示', default=True)
    sort = models.IntegerField('排序', default=0)
    username = models.CharField('账号', max_length=32, null=True, blank=True)
    password = models.CharField('密码', max_length=32, null=True, blank=True)

    category = models.ForeignKey(SubCategory, on_delete=models.PROTECT)

    class Meta:
        verbose_name = '站点'
        verbose_name_plural = verbose_name
        ordering = ['-sort']


DEVICE_STATUS_CHOICES = ((0, "禁用"), (1, "启用"))


class Deviceinfo(models.Model):
    username = models.CharField('账号', max_length=255, null=True, blank=True)
    password = models.CharField('密码', max_length=255, null=True, blank=True)
    name = models.CharField('联系人', max_length=20, null=True, blank=True)
    remarks = models.TextField('备注', null=True, blank=True)


class Device(PublicModel, models.Model):
    dev_type = models.CharField('设备类型', max_length=20, null=True, blank=True)
    name = models.CharField('设备名称', max_length=20, null=True, blank=True)
    sort = models.IntegerField('排序', default=1)
    address = models.CharField('使用位置', max_length=20, null=True, blank=True)
    number = models.IntegerField('数量', default=1)
    status = models.IntegerField('设备状态', default=1, choices=DEVICE_STATUS_CHOICES)
    remarks = models.TextField('备注', null=True, blank=True)
    dev_info = models.ForeignKey(Deviceinfo, on_delete=models.CASCADE, verbose_name="设备信息", null=True, blank=True)

    class Meta:
        verbose_name = '设备管理'
        verbose_name_plural = verbose_name
        ordering = ['-sort']

    def __str__(self):
        return self.name


class AbsoTotal(PublicModel, models.Model):
    type_order = models.CharField('类型', max_length=20, null=True, blank=True)
    sort = models.IntegerField('排序', default=1)
    total_sales = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总价", default=0)
    total_refund = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="退款金额", default=0)
    remarks = models.TextField('备注', null=True, blank=True)

    @property
    def total_transaction(self):
        return self.total_sales - self.total_refund


class Meta:
    verbose_name = '订单总额统计'
    verbose_name_plural = verbose_name
    ordering = ['-sort']


class NetDevice(models.Model):
    """
    设备模型类
    """
    choice_type = (
        (1, '交换机'),
        (2, '路由器'),
        (3, '防火墙'),
        (4, '未知')
    )
    status_choices = (
        (1, '在线'),
        (2, '离线')
    )
    name = models.CharField(max_length=64, verbose_name='设备名称')
    device_type = models.IntegerField(verbose_name='设备类型', choices=choice_type, default=1)
    ipaddress = models.CharField(max_length=64, verbose_name='设备IP地址')
    status = models.IntegerField(verbose_name='主机状态', choices=status_choices, default=1)
    community = models.CharField(max_length=64, verbose_name='团体名', default="huawei")

    class Meta:
        db_table = 'deviceinfo'
        verbose_name = '设备信息表'
        verbose_name_plural = verbose_name


class Port(models.Model):
    """
    端口模型类
    """
    choice_status = (
        (1, '在线'),
        (2, '离线')
    )
    name = models.CharField(max_length=64, verbose_name='端口名称')
    description = models.CharField(max_length=64, verbose_name='端口描述', null=True, blank=True)
    status = models.IntegerField(verbose_name='端口状态', choices=choice_status, default=1)
    device = models.ForeignKey(NetDevice, on_delete=models.CASCADE, verbose_name='设备')

    class Meta:
        db_table = 'portinfo'
        verbose_name = '端口信息表'
        verbose_name_plural = verbose_name


class Port_Log(models.Model):
    """
    端口日志模型类
    """
    log_time = models.DateTimeField(verbose_name='记录时间', null=True, blank=True)
    traffic_in = models.CharField(max_length=64, verbose_name='流量入')
    traffic_out = models.CharField(max_length=64, verbose_name='流量出')
    port = models.ForeignKey(Port, on_delete=models.CASCADE, verbose_name='端口')

    class Meta:
        db_table = 'portlog'
        verbose_name = '端口日志表'
        verbose_name_plural = verbose_name


class ABSO_order_types(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=64, verbose_name='类型名称')

    class Meta:
        db_table = 'abso_order_types'


class ABSO_order(models.Model):
    code = models.CharField(max_length=64, verbose_name='订单号')
    createTime = models.DateTimeField(verbose_name='订单时间', null=True, blank=True)
    totalprice = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总价")
    payment_method = models.CharField(max_length=64, verbose_name='支付方式', null=True, blank=True)
    status = models.IntegerField(verbose_name='订单状态', default=1)
    user_name = models.CharField(max_length=64, verbose_name='下单人')
    accountPhone = models.CharField(max_length=64, verbose_name='联系电话')
    user_type_name = models.CharField(max_length=64, verbose_name='会员类型')
    type = models.ForeignKey(ABSO_order_types, on_delete=models.CASCADE, verbose_name='订单类型', null=True, blank=True)
    user_address = models.CharField(max_length=64, verbose_name='地址')

    class Meta:
        db_table = 'abso_order'
        verbose_name = '订单信息表'
        verbose_name_plural = verbose_name


class Payment(models.Model):
    name = models.CharField(max_length=64, verbose_name='名称')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="价格")
    sort = models.IntegerField(verbose_name='排序', default=1)
    end_time = models.DateTimeField(verbose_name='结束时间', null=True, blank=True)
    remarks = models.TextField(verbose_name='备注', null=True, blank=True)


class Produce(models.Model):
    add_date = models.DateField(max_length=64, verbose_name='日期')
    category = models.CharField(max_length=32, verbose_name='菜品')
    unit = models.CharField(max_length=32, verbose_name='单位')
    specifications = models.CharField(max_length=64, verbose_name='规格')
    wholesale_price = models.CharField(max_length=64, verbose_name='批发价格')
    price = models.CharField(max_length=64, verbose_name='价格')


###IDC设备管理
class Client(models.Model):
    client_name = models.CharField("客户名称", max_length=100, blank=True, null=True)
    client_abbreviation = models.CharField("客户简称", max_length=50, blank=True, null=True)
    remarks = models.TextField("备注", blank=True, null=True)

    class Meta:
        db_table = 'IDC_Client'

    def __str__(self):
        return self.client_name


class MachineRoom(models.Model):
    room_name = models.CharField("机房名称", max_length=100, blank=False)
    remarks = models.TextField("备注", blank=True, null=True)

    class Meta:
        db_table = 'IDC_Room'

    def __str__(self):
        return self.room_name


class Cabinet(PublicModel, models.Model):
    STATUS_CHOICES = (
        (1, '整租'),
        (2, '散户'),
        (3, '退租'),
    )
    status = models.IntegerField("状态", choices=STATUS_CHOICES, default=1)
    cabinet_number = models.CharField("机柜编号", max_length=20)
    machine_room = models.ForeignKey(verbose_name="所属机房", to=MachineRoom, on_delete=models.PROTECT,
                                     related_name='cabinets')
    remarks = models.TextField("备注", blank=True, null=True)

    class Meta:
        db_table = 'IDC_Cabinet'

    def __str__(self):
        return self.cabinet_number


class IDCDevice(PublicModel, models.Model):
    STATUS_CHOICES = (
        (1, '已缴费'),
        (2, '未交费'),
        (3, '欠费'),
        (4, '最低保证金期'),
    )
    device_type = models.CharField("设备类型", max_length=50)
    brand = models.CharField("设备厂商", max_length=50)
    model = models.CharField("设备型号", max_length=50)
    height = models.IntegerField("设备高度")
    sn = models.CharField("序列号", max_length=50)
    status = models.IntegerField("状态", choices=STATUS_CHOICES, default=1)
    notes = models.TextField(blank=True, null=True)
    memory = models.CharField(max_length=50, blank=True, null=True)
    disk = models.CharField(max_length=50, blank=True, null=True)
    ipmi_ip = models.GenericIPAddressField(null=True, blank=True)
    main_ip = models.GenericIPAddressField(null=True, blank=True)
    os_password = models.CharField(max_length=50, blank=True, null=True)
    vlan = models.CharField(max_length=50, blank=True, null=True)
    device_code = models.CharField(max_length=50, blank=True, null=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    subnet = models.CharField(max_length=50, blank=True, null=True)
    gateway = models.GenericIPAddressField(null=True, blank=True)
    bound_mac = models.CharField(max_length=50, blank=True, null=True)
    cabinet = models.ForeignKey(Cabinet, on_delete=models.CASCADE, related_name='devices', null=False, blank=False)
    client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='devices', null=False, blank=False)
    room = models.ForeignKey(MachineRoom, on_delete=models.CASCADE, related_name='devices', null=False, blank=False)

    def save(self, *args, **kwargs):
        request = kwargs.pop('request', None)
        super().save(*args, **kwargs)
        if request:
            pass

    class Meta:
        db_table = 'IDC_Device'

    def __str__(self):
        return f"{self.device_type} ({self.sn})"


class IDCDeviceLog(models.Model):
    device = models.ForeignKey(IDCDevice, on_delete=models.CASCADE)
    action = models.CharField("操作", max_length=50)
    timestamp = models.DateTimeField("时间戳", auto_now_add=True)
    details = models.TextField("详情", blank=True, null=True)

    class Meta:
        db_table = 'IDC_DeviceLog'

    def __str__(self):
        return f"{self.device.sn} - {self.action} - {self.timestamp}"


### 合同管理
class ContractType(models.Model):
    # 合同类型表，用于分类合同
    name = models.CharField(max_length=100, unique=True)

    class Meta:
        db_table = 'ContractType'
        verbose_name = '合同类型'
        verbose_name_plural = '合同类型'


class ContractStatus(models.Model):
    # 合同状态表
    status = models.CharField(max_length=100, unique=True)

    class Meta:
        db_table = 'ContractStatus'
        verbose_name = '合同状态'


class Contract(PublicModel, models.Model):
    # 合同表，存储与合同相关的所有信息
    title = models.CharField(max_length=255)  # 合同标题
    name = models.CharField(max_length=255)  # 签订单位名称
    contract_type = models.ForeignKey(ContractType, on_delete=models.PROTECT)  # 关联到合同类型，保护模式防止删除关联类型
    status = models.ForeignKey(ContractStatus, on_delete=models.PROTECT)  # 关联到合同状态，保护模式防止删除关联状态
    start_date = models.DateField()  # 合同开始日期
    end_date = models.DateField(null=True, blank=True)  # 合同结束日期，允许为空
    mid = models.CharField(verbose_name='图片id', max_length=64, blank=True, null=True)  # 图片名称
    path = models.CharField(verbose_name='路径', max_length=255, default='', blank=True, null=True)  # 图片路径
    username = models.CharField(verbose_name='用户账号', max_length=32)  # 上传人
    file_name = models.CharField(verbose_name='图片名称', max_length=255, default='')  # 图片名
    description = models.TextField(blank=True, null=True)  # 合同描述，可选字段

    class Meta:
        db_table = 'Contract'
        verbose_name = '合同'
        verbose_name_plural = '合同'
        ordering = ['-id']


class FeeType(str, Enum):
    WATER = 'water'
    ELECTRICITY = 'electricity'
    PROPERTY_MANAGEMENT = 'property_management'

    @classmethod
    def choices(cls):
        return tuple((item.value, item.value.replace('_', ' ').title()) for item in cls)


class FeeStandard(models.Model):
    user = models.ForeignKey(Client, on_delete=models.CASCADE)
    fee_type = models.CharField(max_length=50, choices=FeeType.choices())
    value = models.DecimalField(max_digits=10, decimal_places=2)

    class Meta:
        unique_together = ('user', 'fee_type')  # 确保每个用户对每种费用类型只有一个记录